package cn.openea.perpartner.meily.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.openea.perpartner.common.core.exception.ServiceException;
import cn.openea.perpartner.common.core.web.page.TableDataInfo;
import cn.openea.perpartner.meily.web.entity.GroupBuyingSub;
import cn.openea.perpartner.meily.web.entity.Order;
import cn.openea.perpartner.meily.web.entity.PersonalInfo;
import cn.openea.perpartner.meily.web.entity.ProvideSamplesSub;
import cn.openea.perpartner.meily.web.entity.dto.TrialEvaluationDTO;
import cn.openea.perpartner.meily.web.entity.vo.OrderSearchVo;
import cn.openea.perpartner.meily.web.entity.vo.OrderVo;
import cn.openea.perpartner.meily.web.mapper.OrderMapper;
import cn.openea.perpartner.meily.web.mapper.PersonalInfoMapper;
import cn.openea.perpartner.meily.web.service.IGroupBuyingSubService;
import cn.openea.perpartner.meily.web.service.IOrderService;
import cn.openea.perpartner.meily.web.service.IProvideSamplesSubService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * @author rains
 * @since 2023-05-16 12:16
 */
@Service("orderServiceImpl")
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>  implements IOrderService {

    @Resource
    private IGroupBuyingSubService groupBuyingSubService;
    @Resource
    private IProvideSamplesSubService provideSamplesSubService;

    /**
     * 获取订单列表-订单系统
     * @param vo
     * @return
     */
    @Override
    public List<Order> getOrderListByOrderSys(OrderSearchVo vo) {

        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();

        StringBuffer queryStr = new StringBuffer();

        String extra_sql = "";

        // 关键字搜索
        if(StrUtil.isNotBlank(vo.getSearchStr())){
            extra_sql = " and goods_name like '%"+vo.getSearchStr()+"%'" ;
        }

        /**
         * 0全部、1待发货、2待收货、3待评价、4已退款
         */
        String type = vo.getType();
        if("0".equals(type)){// 获取全部的订单（1.样品：待支付(不包含此状态)、待发货、已发货、已完成、已评价；2.团购：已付款、已发货、已完成、已退款）
            queryStr.append(" and create_user = '"+vo.getUserId()+"' ");
            queryStr.append(" and ( ");
            queryStr.append(" order_id in (select order_id from meily_provide_samples_sub where order_status <> '待支付' " + extra_sql  + " ) ");
            queryStr.append(" or order_id in (select order_id from meily_group_buying_sub where 1=1 "+ extra_sql + ") ");
            queryStr.append(" ) ");

        } else if("1".equals(type)){// 获取待发货的订单
            queryStr.append(" and create_user = '"+vo.getUserId()+"' ");
            queryStr.append(" and ( ");
            queryStr.append(" order_id in (select order_id from meily_provide_samples_sub where order_status = '待发货' " + extra_sql + " ) ");
            queryStr.append(" or order_id in (select order_id from meily_group_buying_sub where order_status = '已付款' " + extra_sql + ") ");
            queryStr.append(" ) ");

        } else if("2".equals(type)){// 获取待收货的订单
            queryStr.append(" and create_user = '"+vo.getUserId()+"' ");
            queryStr.append(" and ( ");
            queryStr.append(" order_id in (select order_id from meily_provide_samples_sub where order_status = '已发货' " + extra_sql + ") ");
            queryStr.append(" or order_id in (select order_id from meily_group_buying_sub where order_status = '已发货' " + extra_sql + ") ");
            queryStr.append(" ) ");

        } else if("3".equals(type)){// 获取待评价的订单
            queryStr.append(" and create_user = '"+vo.getUserId()+"' ");
            queryStr.append(" and ( ");
            queryStr.append(" order_id in (select order_id from meily_provide_samples_sub where order_status = '已完成' " + extra_sql + ") ");
            queryStr.append(" or order_id in (select order_id from meily_group_buying_sub where order_status = '已完成' " + extra_sql + ") ");
            queryStr.append(" ) ");

        } else if("4".equals(type)){// 获取已退款的订单
            queryStr.append(" and create_user = '"+vo.getUserId()+"' ");
            queryStr.append(" and ( ");
            queryStr.append(" order_id in (select order_id from meily_provide_samples_sub where order_status = '已退款' " + extra_sql + ") ");
            queryStr.append(" or order_id in (select order_id from meily_group_buying_sub where order_status = '已退款' " + extra_sql + ") ");
            queryStr.append(" ) ");

        } else {
            throw new ServiceException("获取不到参数type!");
        }

        queryWrapper.last(" " + queryStr + " order by create_time desc ");

        return baseMapper.getList(queryWrapper);

        /*// 订单系统-获取订单列表
        JSONObject object = new JSONObject();
        object.put("pageSize", vo.getPageSize());
        object.put("pageNum", vo.getPageNum());
        object.put("userId", vo.getUserId());
        object.put("searchStr", vo.getSearchStr());
        object.put("orderType", vo.getOrderType());
        object = getToken(object);
        JSONObject resObj = getOrderList2ByOrderSys(object);
        if (resObj.isEmpty() || !"200".equals(resObj.getString("code"))) {
            throw new ServiceException("获取订单列表出错了！");
        }

        JSONArray array = resObj.getJSONArray("rows");
        List<Order> list = JSON.parseArray(array.toJSONString(), Order.class);

        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(list);
        tableDataInfo.setTotal(resObj.getLong("total"));

        return tableDataInfo;*/
    }

    /**
     * 组装业务数据
     * @param listSys
     * @return
     */
    @Override
    public List<OrderVo> assemblyData(List<Order> listSys) {

        List<OrderVo> orderList = new ArrayList<>();

        /**
         * 全部：全部订单，包括商品团购和样品推广
         * 待发货：就是用户已付款的订单，订单列表的右上角和订单详情都要改成【待发货】
         * 待收货：就是平台已发货的订单，订单列表的右上角和订单详情都要改成【待收货】
         * 待评价：就是用户已确认收货（样品已签收）的订单，订单列表的右上角和订单详情都要改成【待评价】，评价后状态改成【已评价】
         * 已退款：就是完成退款的订单，订单列表的右上角和订单详情都要改成【已退款】
         */
        // 遍历订单列表，组装业务数据
        for(Order order : listSys){
            OrderVo vo1 = new OrderVo();
            BeanUtil.copyProperties(order, vo1, true);

            // 团购。订单状态：已付款、已发货、已完成、已退款；(默认已付款)
            if("meily_group_buying_sub".equals(order.getSourceModule())){
                // 获取团购购买记录详情
                LambdaQueryWrapper<GroupBuyingSub> groupWrapper = new LambdaQueryWrapper<>();
                groupWrapper.eq(GroupBuyingSub::getOrderId, order.getOrderId());
                GroupBuyingSub groupBuyingSub = groupBuyingSubService.getOne(groupWrapper);
                if(groupBuyingSub != null && BeanUtil.isNotEmpty(groupBuyingSub)){
                    vo1.setGoodsId(groupBuyingSub.getGoodsId());
                    vo1.setGoodsNo(groupBuyingSub.getGoodsNo());
                    vo1.setGoodsName(groupBuyingSub.getGoodsName());
                    vo1.setSpecification(groupBuyingSub.getSpecification());
                    vo1.setBuyQuantity(groupBuyingSub.getBuyQuantity());
                    vo1.setEvaluationContent(groupBuyingSub.getEvaluationContent());
                    vo1.setBusinessId(groupBuyingSub.getId());
                    vo1.setMainId(groupBuyingSub.getMainDocunid());
                    vo1.setOrderStatus(groupBuyingSub.getOrderStatus());// 以业务表的订单状态为准
                    if("已付款".equals(vo1.getOrderStatus())){
                        vo1.setOrderStatus("待发货");
                    }
                    if("已发货".equals(vo1.getOrderStatus())){
                        vo1.setOrderStatus("待收货");
                    }
                    if("已完成".equals(vo1.getOrderStatus())){
                        vo1.setOrderStatus("待评价");
                    }
                    vo1.setAddress(groupBuyingSub.getAddress());
                    vo1.setGrade("");
                    orderList.add(vo1);
                }
            }

            // 样品。订单状态：待支付、待发货、已发货、已完成、已评价；(默认待发货)
            if("meily_provide_samples_sub".equals(order.getSourceModule())){
                // 获取样品领取记录详情
                LambdaQueryWrapper<ProvideSamplesSub> samplesWrapper = new LambdaQueryWrapper<>();
                samplesWrapper.eq(ProvideSamplesSub::getOrderId, order.getOrderId());
                ProvideSamplesSub provideSamplesSub = provideSamplesSubService.getOne(samplesWrapper);
                if(provideSamplesSub != null && BeanUtil.isNotEmpty(provideSamplesSub)){
                    vo1.setGoodsId(provideSamplesSub.getGoodsId());
                    vo1.setGoodsNo(provideSamplesSub.getGoodsNo());
                    vo1.setGoodsName(provideSamplesSub.getGoodsName());
                    vo1.setSpecification(provideSamplesSub.getSpecification());
                    vo1.setBuyQuantity(provideSamplesSub.getQuantity());
                    vo1.setEvaluationContent(provideSamplesSub.getFeedbackContent());
                    vo1.setBusinessId(provideSamplesSub.getId());
                    vo1.setMainId(provideSamplesSub.getMainId());
                    vo1.setOrderStatus(provideSamplesSub.getOrderStatus());// 以业务表的订单状态为准
                    if("已发货".equals(vo1.getOrderStatus())){
                        vo1.setOrderStatus("待收货");
                    }
                    if("已完成".equals(vo1.getOrderStatus())){
                        vo1.setOrderStatus("待评价");
                    }
                    vo1.setGrade(provideSamplesSub.getGrade());
                    JSONObject obj = new JSONObject();
                    obj.put("Name", provideSamplesSub.getConsigneeName());
                    obj.put("PhoneNum", provideSamplesSub.getConsigneePhoneNum());
                    obj.put("Region", "");
                    obj.put("StreetVillage", "");
                    obj.put("Address", "");

                    if(StrUtil.isNotBlank(provideSamplesSub.getConsigneeAddress())){
                        if(provideSamplesSub.getConsigneeAddress().split(" ").length == 2){
                            String addressStr = provideSamplesSub.getConsigneeAddress().split(" ")[0];
                            String[] arr = addressStr.split("-");
                            if(arr.length == 5){
                                String Region = arr[0] + "-" + arr[1] + "-" + arr[2];
                                String StreetVillage = arr[3] + "-" + arr[4];
                                obj.put("Region", Region);
                                obj.put("StreetVillage", StreetVillage);
                            }
                            obj.put("Address", provideSamplesSub.getConsigneeAddress().split(" ")[1]);
                        }
                    }

                    vo1.setAddress(obj.toJSONString());

                    orderList.add(vo1);
                }
            }
        }

        return orderList;
    }

}
